/**
 * Five-xlx 2015.9.1
 * QQ:673921852
 **/
var URL='http://new.rubulls.com/',
//var URL='192.168.1.5',
	pUrl;

(function($, owner) {
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
	
		if (loginInfo.account.length < 2) {
			return callback('账号最短为 2 个字符');
		}
		if (loginInfo.password.length < 6) {
			return callback('密码最短为 6 个字符');
		}
		var waitLogin = plus.nativeUI.showWaiting();
		$.ajax(URL+'api/Login/GetUser',{
			data:{
				userName:loginInfo.account,
				password:loginInfo.password
			},
			dataType:'json',
			type:'get',
			timeout:10000,
			success:function(data){
				waitLogin.close();
				if(data.Success=="true"){
					return owner.createState(loginInfo.account,data.UserId, callback);
				}else{
					callback('用户名或密码错误');
				}
			},
			error:function(xhr,type,errorThrown){
				waitLogin.close();
				callback('请求失败，请检查网络')
			}
		});
	};
	owner.createState = function(name,userId, callback) {
		var state = owner.getState();
		state.account = name;
		state.userId = userId;
		state.token = "token123456789";
		owner.setState(state);
		return callback();
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if (regInfo.account.length < 4) {
			return callback('用户名最短需要 4 个字符');
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		/*if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}*/
		var waitReg = plus.nativeUI.showWaiting();
		var data=JSON.stringify({userName:regInfo.account,password:regInfo.password});
		console.log(data)
		$.ajax(URL+'api/Register/PostRegisterUser',{
			data: data,
			dataType:'json',
			contentType:'application/json',
			type:'post',
			timeout:10000,
			success:function(data){
				console.log(JSON.stringify(data))
				waitReg.close();
				if(data.Success=="true"){
					return callback();
				}else{
					return callback('用户名已被注册');
				}
			},
			error:function(xhr,type,errorThrown){
				waitReg.close();
				return callback('请求失败，请检查网络')
			}
		});
		
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '暂不支持邮箱找回密码功能，请前往PC端找回密码' /*'新的随机密码已经发送到您的邮箱，请查收邮件。'*/);
	};

	/**
	 * 设置应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 获取应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}
	
	//判断是否是ios
	owner.ios = function() {
		if (plus.os.name.toLocaleLowerCase() == 'ios') {
			return true;
		} else {
			return false;
		}
	};
	
	//IOS判断QQ是否已经安装
	owner.isQQInstalled = function() {
		console.log(TencentOAuth)
		var TencentOAuth = plus.ios.import("TencentOAuth");
		var isQQInstalled = TencentOAuth.iphoneQQInstalled();
		return isQQInstalled == '0' ? false : true
	};
	//IOS判断微信是否已经安装
	owner.isWXInstalled = function() {
		var Weixin = plus.ios.import("WXApi");
		var isWXInstalled = Weixin.isWXAppInstalled();
		return isWXInstalled == '0' ? false : true;
	};
	
	/*大于零显示元素*/
	owner.whichShow = function(data,obj) {
		if(data>0){
			document.getElementById(obj).innerText=data.toString();
			document.getElementById(obj).style.display='block';
		}else{
			document.getElementById(obj).style.display='none';
		}
			
	}
	
	/*不为空显示*/
	owner.nullShow = function(data,obj) {
		if(data!=''&&data!=null){
			document.getElementById(obj).innerText=data;
			document.getElementById(obj).style.display='block';
		}else{
			document.getElementById(obj).style.display='none';
		}
			
	}
	
	 //阻止a链接跳转
	owner.stopHref = function(obj) {
		obj.on('tap', 'a', function(e) {
			e.preventDefault();
		});
	}
	
	owner.trim = function(str) {　　
		return str.replace(/(^\s*)|(\s*$)/g, "");　　
	}
	
	owner.isLogin = function(){
		var userState = JSON.parse(localStorage.getItem('$state') || "{}");
		if (userState.userId && userState.userId != '') {
			return true;
		} else {
			return false;
		}
	}
	
	 /**
	  * 重写退出应用
	  **/
	owner.quitApp = function() {
		$.oldBack = mui.back;
		var backButtonPress = 0;
		$.back = function(event) {
			backButtonPress++;
			if (backButtonPress > 1) {
				plus.runtime.quit();
			} else {
				plus.nativeUI.toast('再按一次退出儒牛网');
			}
			setTimeout(function() {
				backButtonPress = 0;
			}, 1000);
			return false;
		};
	}
	
	 //打开软键盘
	owner.openSoftKeyboard = function() {
		if (mui.os.ios) {
			var webView = plus.webview.currentWebview().nativeInstanceObject();
			webView.plusCallMethod({
				"setKeyboardDisplayRequiresUserAction": false
			});
		} else {
			var webview = plus.android.currentWebview();
			plus.android.importClass(webview);
			webview.requestFocus();
			var Context = plus.android.importClass("android.content.Context");
			var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
			var main = plus.android.runtimeMainActivity();
			var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
		}
	};
	
	 //充值验证
	owner.rechargeVerify=function(cardinfo,callback){
		callback = callback || $.noop;
		cardinfo = cardinfo || {};
		cardinfo.account = cardinfo.account || '';
		cardinfo.password = cardinfo.password || '';
		console.log(cardinfo.account.length+","+cardinfo.password.length)
		if(cardinfo.account.length!=0&&cardinfo.password.length!=0){
			if (cardinfo.account.length < 12) {
				return callback('卡号最短为 12 个字符');
			}
			if (cardinfo.password.length < 6) {
				return callback('密码最短为 6 个字符');
			}
		}else{
			return callback('卡号或密码不能为空');
		}
		var waitLogin = plus.nativeUI.showWaiting();
		$.ajax(URL+'api/UserIntegral/GetCheckCardNumAndCardPass',{
			data:{
				CardNum:cardinfo.account,
				CardPass:cardinfo.password
			},
			dataType:'json',
			type:'get',
			timeout:10000,
			success:function(data){
				console.log(data);
				waitLogin.close();
				if(data.success==true){
					callback(data.msg);
				}else{
					callback(data.msg);
				}
			},
			error:function(xhr,type,errorThrown){
				waitLogin.close();
				callback('请求失败，请检查网络')
			}
		});
	};
}(mui, window.app = {}));

function showLogin(url){
	pUrl='login.html';
	if(url=='/'){
		pUrl='../login.html'
	}
	plus.nativeUI.toast('请先登录')
	mui.openWindow({
		id:'login.html',
		url:pUrl,
		show: {
			autoShow:true,
			aniShow: 'zoom-fade-out'
		},
		waiting: {
			autoShow: false
		}
	});
}

function showProduct(id,url){
	var detailPage=plus.webview.getWebviewById('detail.html');
	if(detailPage!=null){
		detailPage.hide();
		detailPage.close();
	}
	pUrl='detail.html';
	if(url=='/'){
		pUrl='../detail.html'
	}
	
	setTimeout(function(){
		mui.openWindow({
			id:'detail.html',
			url:pUrl,
			extras:{
				productId:id
		    },
			show: {
				autoShow:true,
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	},100)
	
}

function showVshop(vshopid,url){
	pUrl='vshop-detail.html';
	if(url=='/'){
		pUrl='vshop/vshop-detail.html'
	}
	mui.openWindow({
		id:'vshop-detail.html',
		url:pUrl,
		extras:{
			vshopId:vshopid
	    },
		show: {
			autoShow:true,
			aniShow: 'pop-in'
		},
		waiting: {
			autoShow: false
		}
	});
}

function reloadWvLoad(){
	var errorText = document.createElement('div');
    errorText.innerHTML = '<h4>网络不给力，请检查网络！</h4><button id="reloadWv" class="mui-btn mui-btn-negative">重新加载</button>';
    errorText.setAttribute('class','empty-show');
    document.body.appendChild(errorText);
	
}

function getIndex(obj){
	var parentN=obj.parentNode.childNodes;
	for(var i=0; i<parentN.length; i++){
		if(obj==parentN[i])
			return i;
	}
}

mui('body').on('tap', '#closeWv', function() {
	if(plus.webview.currentWebview().parent()!=null)
		plus.webview.currentWebview().parent().close();
	else
		plus.webview.currentWebview().close();
});

mui('body').on('tap', '#reloadWv', function() {
	plus.webview.currentWebview().reload();
});

mui('body').on('tap', '.c-href', function() {
	var href=this.getAttribute('data-href').toLowerCase(),
		id;
	if(href.indexOf('product/detail/')>=0){
		id=href.split('product/detail/')[1];
		showProduct(id);
	}else if(href.indexOf('topic/detail/')>=0){
		id=href.split('topic/detail/')[1];
		mui.openWindow({
			id:'topic-detail.html',
			url:'topic-detail.html',
			extras:{
				topicId:id
		    },
			show: {
				autoShow:true,
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	}
	
});

mui('body').on('tap', '.b-href', function() {
	var href=this.getAttribute('data-href').toLowerCase(),
		id;
	if(href.indexOf('product/detail/')>=0){
		id=href.split('product/detail/')[1];
		showProduct(id,'/');
	}else if(href.indexOf('topic/detail/')>=0){
		id=href.split('topic/detail/')[1];
		mui.openWindow({
			id:'topic-detail.html',
			url:'../topic-detail.html',
			extras:{
				topicId:id
		    },
			show: {
				autoShow:true,
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	}
	
});
/XK金豆商城详情页面跳转/
function showIntegraldetail(id,url){
	var detailPage=plus.webview.getWebviewById('IntegralMall-detail.html');
	if(detailPage!=null){
		detailPage.hide();
		detailPage.close();
	}
	pUrl='IntegralMall-detail.html';
	if(url=='/'){
		pUrl='../IntegralMall-detail.html'
	}
	setTimeout(function(){
		mui.openWindow({
			id:'IntegralMall-detail.html',
			url:pUrl,
			extras:{
				giftListId:id
		    },
			show: {
				autoShow:true,
				aniShow: 'pop-in'
			},
			waiting: {
				autoShow: false
			}
		});
	},100)
}


